package com.seata.account.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.seata.account.po.Account;
import com.seata.account.service.AccountService;
import com.seata.config.CommonResult;
import io.seata.spring.annotation.GlobalLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * TODO
 *
 * @author zxx
 * @version 1.0
 * @date 2021/5/27 11:56
 */
@RequestMapping(value = "/account")
@RestController
public class AccountController {

    @Autowired
    private AccountService accountService;

    /**
     * 扣减账户余额
     */
    @PostMapping("/add")
    public CommonResult add(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money) {
        Account account = get(userId);
        if(account == null){
            accountService.save(Account.builder().userId(userId).total(money).build());
        }else {
            accountService.update(Account.builder()
                    .total(account.getTotal().add(money))
                    .build()
                    ,new UpdateWrapper<Account>()
                    .lambda()
                    .eq(Account::getId,account.getId())
            );
        }
        return new CommonResult(get(userId),"添加账户成功！", 200);
    }

    @GlobalLock
    @RequestMapping("/get")
    public Account get(@RequestParam("userId") Long userId) {
        Account account = accountService.getOne(
                new QueryWrapper<Account>()
                        .lambda()
                        .eq(Account::getUserId,userId)
        );
        return account;
    }

    @GlobalLock
    @PostMapping("/decrease")
    public CommonResult decrease(
            @RequestParam("userId") Long userId
            , @RequestParam("money") BigDecimal money
            , @RequestParam(value = "commit",required = false,defaultValue = "true") boolean commit
    ) {
        accountService.decrease(userId, money,commit);
        return new CommonResult(get(userId),"扣减账户余额成功！", 200);
    }

}
